#include "uart.h"
#include "motor.h"
#include <stdio.h>

// 移除这里的定义，改为 extern 声明
extern uint8_t current_cmd;

// 串口1配置 (调试串口)
void UART1_Configuration(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;
    
    // 使能时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
    
    // 配置TX (PA9) 为推挽复用输出
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    
    // 配置RX (PA10) 为浮空输入
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    
    // 串口参数配置
    USART_InitStructure.USART_BaudRate = 115200;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    
    USART_Init(USART1, &USART_InitStructure);
    USART_Cmd(USART1, ENABLE);
    
    // 使能接收中断
    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
    
    // 清除可能的接收缓冲区数据
    while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) != RESET) {
        USART_ReceiveData(USART1);  // 读取并丢弃数据
    }
}

// 串口3配置 (命令接收串口)
void UART3_Configuration(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;
    
    // 使能时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
    
    // 配置TX (PB10) 为推挽复用输出
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
    
    // 配置RX (PB11) 为浮空输入
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
    
    // 串口参数配置
    USART_InitStructure.USART_BaudRate = 115200;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    
    USART_Init(USART3, &USART_InitStructure);
    USART_Cmd(USART3, ENABLE);
    
    // 使能接收中断
    USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
    
    // 清除可能的接收缓冲区数据
    while(USART_GetFlagStatus(USART3, USART_FLAG_RXNE) != RESET) {
        USART_ReceiveData(USART3);  // 读取并丢弃数据
    }
}

// 中断配置 - 诊断步骤3
void NVIC_Configuration(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;
    
    // 配置NVIC分组
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);  // 2位抢占优先级，2位子优先级
    
    // 配置USART1中断（调试串口）
    NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;  // 降低优先级，避免打断电机控制
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
    
    // 配置USART3中断（命令接收串口）
    NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;  // 相同抢占优先级
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;  // 稍高的子优先级
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
    
    // 添加调试信息
    USART_SendString(USART1, (uint8_t*)"NVIC Configuration Complete\r\n");
}

// 通用串口发送字符串函数
void USART_SendString(USART_TypeDef* USARTx, uint8_t *str)
{
    while(*str)
    {
        USART_SendData(USARTx, *str++);
        while(USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET);
    }
}

// 处理串口命令
void Process_Command(uint8_t data)
{
    // 过滤掉非打印字符（回车、换行、空格等）
    if(data == '\r' || data == '\n' || data == ' ' || data == '\t') {
        return;  // 忽略这些字符，不处理
    }
    
    switch(data)
    {
        case 'f':  // 前进
            Motor_Forward();
            current_cmd = 'f';
            USART_SendString(USART1, (uint8_t*)"Command: Forward - Both wheels moving!\r\n");
            break;
        case 's':  // 后退
            Motor_Backward();
            current_cmd = 's';
            USART_SendString(USART1, (uint8_t*)"Command: Backward - Both wheels moving!\r\n");
            break;
        case 'l':  // 左转
            Motor_Left();
            current_cmd = 'l';
            USART_SendString(USART1, (uint8_t*)"Command: Left - Right wheel moving!\r\n");
            break;
        case 'r':  // 右转
            Motor_Right();
            current_cmd = 'r';
            USART_SendString(USART1, (uint8_t*)"Command: Right - Left wheel moving!\r\n");
            break;
        case '0':  // 停止
            Motor_Stop();
            current_cmd = 'S';
            USART_SendString(USART1, (uint8_t*)"Command: Stop - All wheels stopped!\r\n");
            break;
        case 'd':  // 调试命令
            USART_SendString(USART1, (uint8_t*)"Debug - Motor Status:\r\n");
            Motor_Debug_Status();
            break;
        default:
            // 只显示可打印字符的未知命令
            if(data >= 32 && data <= 126) {  // 可打印ASCII字符范围
                USART_SendString(USART1, (uint8_t*)"Unknown command: ");
                USART_SendData(USART1, data);
                USART_SendString(USART1, (uint8_t*)"\r\n");
            }
            break;
    }
}

// 串口1中断处理函数
void USART1_IRQHandler(void)
{
    uint8_t data;
    
    if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
    {
        data = USART_ReceiveData(USART1);
        Process_Command(data);
        USART_ClearITPendingBit(USART1, USART_IT_RXNE);
    }
}

// 串口3中断处理函数
void USART3_IRQHandler(void)
{
    uint8_t data;
    
    if (USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)
    {
        data = USART_ReceiveData(USART3);
        Process_Command(data);
        USART_ClearITPendingBit(USART3, USART_IT_RXNE);
    }
}